<template>
	<view>
		<navbar name="血糖录入"></navbar>
		<view class="equipmentbg" v-if="receiveText==''">
			<view class="equipmentxy">
				<!-- <button @tap="startTest" :disabled="btndis">{{btnText}}</button> -->
				<view class="buzhou-one">
					<text class="bz-text">步骤1</text>请先确认设备处于工作状态，并打开手机蓝牙功能
				</view>
				<view class="buzhou-one" style="top:555upx">
					<text class="bz-text">步骤2</text>手机与设备连接成功后，采血针在手指上刺破手指
					后，试纸碰触血液。血糖仪发出一声运行的声音。
				</view>
				<view class="buzhou-one" style="top:1140upx;">
					<text class="bz-text">步骤3</text>测量结束后请耐心等待测量结果
				</view>
			</view>
		</view>
		<view v-if="receiveText!=''">
			<view class="time-interval">
				<view class="interval-view">
					时间段
				</view>
				<view class="interval-flex">
					<view class="flex-item" v-for="(item,index) in selectorList" :key="index" :class="selectorIndex == index?'selector':''" @tap="selector(index)">
						{{item.name}}
					</view>
					<view style="width: 160rpx;"></view>
					<view style="width: 160rpx;"></view>
					<view style="width: 160rpx;"></view>
				</view>
			</view>

			<view class="bloodSugar-flex">
				<view class="sugar-left">
					血糖值
				</view>
				<view class="sugar-right">
					{{receiveText}}  mmol/L
				</view>
			</view>
			<button class="relevance-btn" type="default" @tap="addRecord()">保存</button>
		</view>
		<!-- 测量血糖结果:{{receiveText}}  mmol/L -->
	</view>
</template>

<script>
	import dayjs from '@/common/utils/day/day.js'
	export default {
		data() {
			return {
				selectorIndex:0,
				selectorList: [{
					name: '空腹'
				}, {
					name: '早餐后'
				}, {
					name: '午餐前',
					// count: 5
				}, {
					name: '午餐后',
				}, {
					name: '晚餐前',
				}, {
					name: '晚餐后',
				}, {
					name: '凌晨',
				}],
				chooseType: 'Bioland-BGM', //血压计
				inputText: 'Hello World!',
				receiveText: '',
				name: '',
				connectedDeviceId: '',
				services: {},
				characteristics: {},
				connected: true,
				//		判断是否主动断开
				activeClose: false,
				serviceId: '',
				notifyCharacteristicsId: '',
				writeCharacteristicsId: '',
				pakInfoList: [],
				scorollTop: 100,


				clockInOrNot: false, //是否通过打卡进入
			}
		},
		onLoad(e) {
			if (e.type == 1) {
				this.clockInOrNot = true
			} else {
				this.clockInOrNot = false
			}
			this.BleInitialonlaod();
			this.Search()
			//	  屏幕保存常亮
			wx.setKeepScreenOn({
				keepScreenOn: true
			})
		},
		onUnload() {
			// 页面隐藏
			var that = this;
			wx.hideLoading()
			//  终止监听设备
			if (this.searching) {
				wx.stopBluetoothDevicesDiscovery({
					success: function(res) {
						that.searching = false
					}
				})
			}
			this.closeBleFun();
		},
		methods: {
			selector(index){
				this.selectorIndex = index
			},
			// 血糖记录
			addRecord() {
				this.disabled = true;
				let time = new Date( +new Date() + 8 * 3600 * 1000 ).toJSON().substr(0,19).replace("T"," ")
				let _this = this,
					fdata = {
						// sugarValue:blood,
						deviceType:'BLOOD_SUGAR',
						recordTime: dayjs(time).format('YYYY-MM-DD'),
						createTime:time,
						userId: uni.getStorageSync(global.IS_DEV?'USER_DATA_BSY_T':'USER_DATA_BSY_Z').userId,
						inputType:2,//1手动 2设备
						timeSlot:this.selectorIndex+1,//血糖时段
						mac:this.name,//设备mac
						deviceId:this.connectedDeviceId,//设备id
						healthDataId:'',
						healthData:JSON.stringify({sugarValue:this.receiveText}),

					};
				// return
				this.$api.post(global.apiUrls.addRecord, fdata).then(res => {
					if (res.data.code == 1000) {
						_this.bloodGlucoseNum = 0
						_this.value1=''
						uni.showToast({
							title: res.data.message,
							duration: 2000
						});
						if (_this.clockInOrNot) {
							let pages = getCurrentPages(); //当前页面栈
							let beforePage = pages[pages.length - 2]; //指定调用页面为上个页面
							beforePage.$vm.punchTheClock() //getData 是你要调用上个页面的方法，微信小程序不需要用 $vm
						}
						console.log('走到跳转界面了吗')
						uni.navigateBack({
							delta: 1
						});

					} else {
						uni.showToast({
							title: res.data.message,
							icon: "none",
							duration: 2000
						});
					}
					_this.disabled = false;
				}).catch(err => {
					_this.disabled = false;
				})
			},
			// 蓝牙初始化
			BleInitialonlaod() {
				let that = this;
				console.log('onLoad');
				wx.onBluetoothAdapterStateChange(function(res) {
					console.log(res)
					that.searching = res.discovering
					if (!res.available) {
						that.searching = false
					}
				})
				wx.onBluetoothDeviceFound(function(devices) {

					let name = devices.devices[0].name
					if (name == that.chooseType) {
						console.log('获取蓝牙设备') //蓝牙设备列表
						console.log(devices.devices[0]) //蓝牙设备列表
						console.log(devices.devices[0].name) //蓝牙设备列表
						console.log(devices.devices[0])
						that.Connect(devices.devices[0])
					}
				})
			},
			// 连接设备
			Connect(data) {
				console.log(data, 7777777777777)
				var that = this
				//		chooseType: Bioland-BGM=>血糖仪       Bioland-BPM==>血压计
				let chT = this.chooseType;
				wx.stopBluetoothDevicesDiscovery({
					success: function(res) {
						console.log(res)
						that.searching = false
					}
				})
				wx.showLoading({
					title: '连接设备中...',
				})
				wx.createBLEConnection({
					deviceId: data.deviceId,
					success: function(res) {
						console.log(res)
						wx.hideLoading()
						wx.showToast({
							title: '连接成功',
							icon: 'success',
							duration: 1000
						})
						that.BleInitial({
							connectedDeviceId: data.deviceId,
							name: data.name
						})

						uni.showLoading({
							title: '测量中'
						});
					},
					fail: function(res) {
						console.log(res)
						wx.hideLoading()
						wx.showModal({
							title: '提示',
							content: '连接失败',
							showCancel: false,
							success: function(res) {
								// uni.navigateBack({
								// 	delta: 1
								// })
								that.baclkFun()
							},
						})
					}
				})
			},
			Search() {
				wx.showLoading({
					title: '搜索设备中...',
				})
				var that = this
				if (!that.searching) {
					wx.closeBluetoothAdapter({
						complete: function(res) {
							console.log(res)
							wx.openBluetoothAdapter({
								success: function(res) {
									console.log(res)
									wx.getBluetoothAdapterState({
										success: function(res) {
											console.log(res)
										}
									})
									wx.startBluetoothDevicesDiscovery({
										allowDuplicatesKey: false,
										success: function(res) {
											console.log(res)
											that.searching = true;
										}
									})
								},
								fail: function(res) {
									wx.hideLoading()
									console.log(res)
									wx.showModal({
										title: '提示',
										content: '请检查手机蓝牙是否打开',
										showCancel: false,
										success: function(res) {
											uni.navigateBack({
												delta: 1
											});
											that.searching = false
										}
									})
								}
							})
						}
					})
				} else {
					wx.stopBluetoothDevicesDiscovery({
						success: function(res) {
							console.log(res)
							that.searching = false
						}
					})
				}
			},
			pakInfoFun(Text, data) {
				let paL = this.pakInfoList
				let inf
				inf = Text + data;
				let sT = this.scorollTop + 50;
				paL.push(inf)
				this.pakInfoList = paL
				this.scorollTop = sT
			},
			//	断开连接
			closeBleFun() {
				let that = this;
				wx.closeBLEConnection({
					deviceId: this.connectedDeviceId,
					success: function() {
						console.log('close sucess')
						that.activeClose = true
					}
				})
			},
			//	返回
			baclkFun() {
				this.closeBleFun();
				uni.navigateBack({
					delta: 1
				})
			},
			BlelinkFail() {
				let that = this;
				setTimeout(function() {
					//			判断,如果不是主动断开连接,则提示弹框
					if (!that.activeClose) {
						wx.showModal({
							title: '提示',
							showCancel: false,
							content: '蓝牙已断开连接，请确定返回重新连接？',
							success(res) {
								that.baclkFun()
							}
						})
					}
				}, 500)
			},
			//	设备蓝牙匹配，发送数据包
			BleInitial(options) {
				var that = this
				that.name = options.name,
					that.connectedDeviceId = options.connectedDeviceId
				//获取蓝牙设备所有服务
				wx.getBLEDeviceServices({
					deviceId: that.connectedDeviceId,
					success: function(res) {
						let seAr = res.services
						seAr.forEach(v => {
							if (v.uuid.indexOf("00001000") > -1) {
								that.serviceId = v.uuid
							}
						})
						//      获取蓝牙某个服务中的所有特征值
						wx.getBLEDeviceCharacteristics({
							deviceId: options.connectedDeviceId,
							serviceId: that.serviceId,
							success: function(res) {
								console.log('对应服务的特征值')
								console.log(res.characteristics)
								//              	 获取到的特征值有多个，最后要用的事能读，能写，能监听的那个值的uuid作为特征值
								let chaArr = res.characteristics
								res.characteristics.forEach(v => {
									if (v.uuid.indexOf("00001002") > -1) {
										that.notifyCharacteristicsId = v.uuid
									}
									if (v.uuid.indexOf("00001001") > -1) {
										that.writeCharacteristicsId = v.uuid
									}
								})
								//启用低功耗蓝牙设备特征值变化时的 notify 功能，订阅特征值。
								//注意：必须设备的特征值支持 notify 或者 indicate 才可以成功调用。
								wx.notifyBLECharacteristicValueChange({
									state: true,
									deviceId: options.connectedDeviceId,
									serviceId: that.serviceId,
									characteristicId: that.notifyCharacteristicsId,
									success: function(res) {
										//发送'00'包,获取设备信息
										that.Send('00');
										console.log('开始发包')
									},
									fail: function(res) {
										console.log(res)
										console.log('开始发包失败')
									}
								})
							}
						})
					}
				})
				//		监听蓝牙状态:包括连接异常/断开连接
				wx.onBLEConnectionStateChange(function(res) {
					console.log(res.connected)
					that.connected = res.connected
					if (!res.connected) {
						that.BlelinkFail();
					}
				})
				//		监听低功耗蓝牙设备的特征值变化事件
				wx.onBLECharacteristicValueChange(function(res) {
					console.log('接收数据');
					console.log(res);
					var receiveText = that.$basejs.buf2hex(res.value);
					console.log('接收到数据：' + receiveText);
					console.log(receiveText.length);
					that.pakInfoFun('接收数据：', receiveText)
					if (receiveText.length == 36 || receiveText.length == 30) {
						let st = receiveText.slice(4, 6);
						console.log(st)
						if (st == '03') {
							//'03':读取血糖数据
							that.Send('03');
						}
						//'03':读取血糖数据
						//				that.Send('03');
					}
					if (receiveText.length == 24) {
						//处理测量结果
						receiveText = that.handleResult(receiveText);
						that.receiveText = receiveText
						uni.hideLoading();
					}

				})
			},
			bindInput(e) {
				this.inputText = e.detail.value
				console.log(e.detail.value)
			},
			//	发包数据处理
			SendData(threeArr) {
				//		let threeArr='00';//第三位数字
				//		获取日期
				let getT = new Date();
				let Ty = '',
					Tm = '',
					Td = '',
					Th = '',
					Tmi = '',
					Ts = '',
					Tdate = '',
					Tadd = '';
				Ty = getT.getFullYear() % 1000;
				Tm = getT.getMonth() + 1;
				Td = getT.getDate();
				Th = getT.getHours();
				Tmi = getT.getMinutes();
				Ts = getT.getSeconds();
				Tdate = Ty + '-' + Tm + '-' + Td + ' ' + Th + ':' + Tmi + ':' + Ts;
				//		获取包的最后一位数字
				Tadd = 90 + 10 + Number(threeArr) + Ty + Tm + Td + Th + Tmi + Ts + 2;
				if (Tadd > 255) {
					//			获取最后两位
					Tadd = (Tadd % 255);
				}
				//		转十六进制
				threeArr = '0x' + threeArr.toString(16);
				Ty = '0x' + Ty.toString(16);
				Tm = '0x' + Tm.toString(16);
				Td = '0x' + Td.toString(16);
				Th = '0x' + Th.toString(16);
				Tmi = '0x' + Tmi.toString(16);
				Ts = '0x' + Ts.toString(16);
				Tadd = '0x' + Tadd.toString(16);
				let sendArr = ['0x5A', '0x0A', threeArr, Ty, Tm, Td, Th, Tmi, Ts, Tadd];

				let val = new Uint8Array(sendArr);
				var receiveText = this.$basejs.buf2hex(val.buffer)
				console.log(threeArr + '--数据：' + receiveText)
				if (threeArr == '0x00') {
					this.pakInfoFun('发送信息读取包00：', receiveText)
				} else if (threeArr == '0x03') {
					this.pakInfoFun('发送数据读取包03：', receiveText)
				}
				return sendArr;
			},
			//	发包
			Send(threeArr) {
				var that = this;
				if (that.connected) {
					//发包内容
					let val = new Uint8Array(that.SendData(threeArr));
					wx.writeBLECharacteristicValue({
						deviceId: that.connectedDeviceId,
						serviceId: that.serviceId,
						characteristicId: that.writeCharacteristicsId,
						value: val.buffer,
						success: function(res) {
							console.log('发包成功')
							console.log(res)
						},
						fail: function(res) {
							console.log(res)
							console.log('发包失败')
						},
						complete: function(res) {
							console.log('完成')
							console.log(res)
						}

					})
				} else {
					that.BlelinkFail();
				}
			},
			//处理得出的结果
			handleResult(data) {
				var testValue1 = data.substr(18, 2),
					testValue2 = data.substr(20, 2);
				var testValue3 = '0x' + testValue2 + testValue1;
				testValue3 = parseInt(testValue3) / 18;
				//四舍五入，保留1位小数toFixed(1)
				testValue3 = testValue3.toFixed(1);
				return testValue3
			},
		}
	}
</script>

<style lang="scss">
	.equipmentbg {
		width: 100vw;
		min-height: 100vh;
		background: url(http://static.bsyjk.cn/equipmentbg/0DB19D05B0D1471BBCBDD70DAEDE2374.png)no-repeat;
		background-size: 100% 100%;

		.equipmentxy {
			width: 750upx;
			height: 1460upx;
			background: url(http://static.bsyjk.cn/bloodSugar/5639BEC8AA684F7E8131A90740F8368A.png)no-repeat;
			background-size: 100% 100%;
			position: relative;
			color: #2EA7E0;
			text-align: center;

			.buzhou-one {
				width: 690upx;
				left: 50%;
				transform: translateX(-50%);
				font-size: 26upx;
				position: absolute;
				top: 74upx;

				.bz-text {
					font-size: 36upx;
					padding-right: 20upx;
				}
			}
		}
	}

	.time-interval {
		width: 750rpx;
		height: 300rpx;
		background: #fff;
		padding: 24rpx 20rpx 0;
		.interval-view {
			font-size: 30rpx;
			color: #333333;
			font-weight: 500;
		}
		.interval-flex{
			display: flex;
			flex-wrap: wrap;
			justify-content: space-between;
		}
		.flex-item{
			width: 160rpx;
			height: 70rpx;
			line-height: 70rpx;
			background: #F5F5F5;
			border-radius: 6px;
			font-size: 30rpx;
			color: #9B9B9B;
			text-align: center;
			margin: 30rpx 0 0;
		}
		.selector{
			background: #2EA7E0;
			color: #fff;
		}
	}
	.bloodSugar-flex{
		width: 750rpx;
		height: 100rpx;
		display: flex;
		background: #fff;
		margin: 30rpx auto 0;
		padding: 30rpx 24rpx 0;
		.sugar-left{
			width: 50%;
			font-size: 28rpx;
			color: #333333;
		}
		.sugar-right{
			width: 50%;
			font-size: 28rpx;
			color: #9B9B9B;
			text-align: right;
		}
	}
	.relevance-btn {
			width: 600upx;
			height: 90upx;
			background: url(https://bsyjk-pic.bsyjk.cn/toprbg/10099E8526734AC383D6ADEED897F016.png)no-repeat;
			background-size: 750upx 375upx;
			border-radius: 45upx;
			font-size: 34upx;
			font-weight: 400;
			color: #FFFFFF !important;
			line-height: 90upx;
			padding: 0;
			margin-top: 272upx;
		}
</style>
